package com.ruoyi.module.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.CullenUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OrderUtils;
import com.ruoyi.module.domain.*;
import com.ruoyi.module.mapper.*;
import com.ruoyi.module.po.OrderDeliveryPo;
import com.ruoyi.module.po.OrderPo;
import com.ruoyi.module.service.IAccountService;
import com.ruoyi.module.service.IFundDetailsService;
import com.ruoyi.module.service.IOrderService;
import com.ruoyi.module.vo.OrderVo;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 *
 * @author fubojin
 * @date 2024-12-06
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private IFundDetailsService fundDetailsService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public Order selectOrderById(Long id) {
        Order order = orderMapper.selectOrderById(id);
        order.setOrderGoodsList(orderGoodsMapper.selectOrderGoodsByOrderId(order.getId()));
        //封装经销商
        return order;
    }

    @Override
    public Order selectOrderByOrderNo(String orderNo) {
        Order order = orderMapper.selectOrderByOrderNo(orderNo);
        order.setOrderGoodsList(orderGoodsMapper.selectOrderGoodsByOrderId(order.getId()));
        //封装经销商
        return order;
    }

    /**
     * 查询订单列表
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectOrderList(Order order) {
        order.setDeleteStatus(0);
        List<Order> orders = orderMapper.selectOrderList(order);
        //封装订单关联商品数据
        orderGoods(orders);
        return orders;
    }

    /**
     * 网页订单查询
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectOrderWebList(Order order) {
        order.setDeleteStatus(0);
        List<Order> orders = orderMapper.selectOrderWebList(order);
        //封装订单关联商品数据
        orderGoods(orders);
        return orders;
    }

    @Override
    public List<Order> distributeList(Order order) {
        order.setDeleteStatus(0);
        List<Order> orders = orderMapper.distributeList(order);
        //封装订单关联商品数据
        orderGoods(orders);
        return orders;
    }

    @Override
    public List<Order> detailedList(Order order) {
        order.setDeleteStatus(0);
        List<Order> orders = orderMapper.detailedList(order);
        //封装订单关联商品数据
        orderGoods(orders);
        return orders;
    }

    /**
     * 封装订单关联商品数据
     *
     * @param orderList 订单List
     */
    void orderGoods(List<Order> orderList) {
        for (Order order : orderList) {
            //片区金额（订单资金明细变动金额）
            FundDetails fundDetails = fundDetailsService.selectFundDetailsByOrderNo(1, order.getOrderNo());
            if (fundDetails != null) {
                order.setFundChangeMoney(fundDetails.getVariableAmount());
            }
            order.setOrderGoodsList(orderGoodsMapper.selectOrderGoodsByOrderId(order.getId()));
        }
    }


    /**
     * 新增订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order insertOrder(Order order) {
        SysUser sysUser = userMapper.selectUserById(order.getUserId());
        Date nowDate = DateUtils.getNowDate();
        order.setCreateTime(nowDate);

        List<OrderGoods> orderGoodsList = order.getOrderGoodsList();
        CullenUtils.validateDataThrowException(orderGoodsList == null || orderGoodsList.size() == 0, "未选择商品,请选择商品!");
        //校验商品库存
        verifyProductInventory(orderGoodsList);

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 创建格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // 格式化日期
        String formattedDate = currentDate.format(formatter);
        order.setOrderNo(OrderUtils.getOrderNo(formattedDate));
        order.setEvaluate(1);
        order.setEnterUserType(sysUser.getEnterUserType());
        if (order.getUserFreight() == null) {
            order.setUserFreight(new BigDecimal(0));
        }
        if (order.getFreight() == null) {
            order.setFreight(new BigDecimal(0));
        }
        if (order.getGoodsGiftMoney() == null) {
            order.setGoodsGiftMoney(new BigDecimal(0));
        }
        order.setUserFreight(new BigDecimal(0));//实付邮费经销商默认0
        order.setDeleteStatus(0);
        orderMapper.insertOrder(order);
        for (OrderGoods orderGoods : orderGoodsList) {
            CullenUtils.validateDataThrowException(orderGoods.getGoodsId() == null, "商品ID不能为空！");
            orderGoods.setCreateTime(nowDate);
            orderGoods.setOrderId(order.getId());
            orderGoodsMapper.insertOrderGoods(orderGoods);
        }

        //处理用户资金变动（扣除保证金）
        if (order.getDistributorId() != null) {
            SysDept sysDept = deptMapper.selectDeptById(order.getDistributorId());
            Account account = accountService.selectAccountByUserId(sysDept.getUserId());
            CullenUtils.validateDataThrowException(account.getAccountBalance().compareTo(order.getOrderTotalMoney()) < 0, "经销商账户余额小于订单总金额无法录入订单！");
            account.setAccountBalance(account.getAccountBalance().subtract(order.getOrderTotalMoney()));
            accountService.updateAccount(account);
        }
        return order;
    }

    //校验商品库存
    void verifyProductInventory(List<OrderGoods> orderGoodsList) {
        for (OrderGoods orderGoods : orderGoodsList) {
            Goods goods = goodsMapper.selectGoodsById(orderGoods.getGoodsId());
            CullenUtils.validateDataThrowException(goods.getGoodsStock() < orderGoods.getGoodsQuantity(), "商品 [" + goods.getGoodsName() + "] 库存不足, 无法下单!");
            //商品库存和销量
            if (goods.getGoodsType() == 3 || goods.getGoodsType() == 4) {
                String goodsList = goods.getGoodsList();
                // 去除首尾的方括号
                String trimmed = goodsList.substring(1, goodsList.length() - 1);
                // 按逗号分割字符串
                String[] stringArray = trimmed.split(",");
                for (int i = 0; i < stringArray.length; i++) {
                    Goods goodsById = goodsMapper.selectGoodsById(Long.parseLong(stringArray[i].trim()));
                    CullenUtils.validateDataThrowException(goodsById.getGoodsStock() < orderGoods.getGoodsQuantity(), "商品 [" + goods.getGoodsName() + "] 库存需要购买库存,无法发货!");
                }
            }
        }
    }

    /**
     * 修改订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        Date nowDate = DateUtils.getNowDate();
        order.setUpdateTime(nowDate);
        int i = orderMapper.updateOrder(order);

        List<OrderGoods> orderGoodsList = order.getOrderGoodsList();
        if (orderGoodsList != null) {
            orderGoodsMapper.deleteOrderGoodsByOrderId(order.getId());
            for (OrderGoods orderGoods : orderGoodsList) {
                CullenUtils.validateDataThrowException(orderGoods.getGoodsId() == null, "商品ID不能为空！");
                orderGoods.setCreateTime(nowDate);
                orderGoods.setOrderId(order.getId());
                orderGoodsMapper.insertOrderGoods(orderGoods);
            }
        }
        return i;
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(Long[] ids) {

        for (Long id : ids) {
            //用户资金变动
            Order order = orderMapper.selectOrderById(id);
            if (order.getDistributorId() != null) {
                SysDept sysDept = deptMapper.selectDeptById(order.getDistributorId());
                Account account = accountService.selectAccountByUserId(sysDept.getUserId());
                account.setAccountBalance(account.getAccountBalance().add(order.getOrderTotalMoney()));
                accountService.updateAccount(account);
            }
            order.setDeleteStatus(1);
            orderMapper.updateOrder(order);
        }

        return 1;
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderById(Long id) {
        orderGoodsMapper.deleteOrderGoodsByOrderId(id);
        return orderMapper.deleteOrderById(id);
    }

    @Override
    public List<Order> orderByEnterUserIdList(Long enterOrderUserId) {
        return orderMapper.orderByEnterUserIdList(enterOrderUserId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDeliveryNo(OrderDeliveryPo orderDeliveryPo) {
        Order order = orderMapper.selectOrderById(orderDeliveryPo.getId());
        if (order.getPayStatus() == 2) {
            throw new ServiceException("订单已经完成无需重复操作");
        }


        //=======================设置订单单号 和 修改订单状态=======================
        order.setDeliveryNo(orderDeliveryPo.getDeliveryNo());
        order.setPayStatus(2);
        order.setUserFreight(orderDeliveryPo.getUserFreight());
        order.setDeliveryTime(DateUtils.getNowDate());
        order.setDeliveryCompany(orderDeliveryPo.getDeliveryCompany());
        orderMapper.updateOrder(order);

        //商品库存管理
        goodsStock(order.getId());

        //订单提成(订单提成)
        if (order.getDistributorId() != null) {
            FundDetails fundDetails = new FundDetails();
            SysDept sysDept = deptMapper.selectDeptById(order.getDistributorId());
            fundDetails.setUserId(sysDept.getUserId());//扣除对应的是经销商
            fundDetails.setDeptId(sysDept.getDeptId());
            fundDetails.setDeptName(sysDept.getDeptName());

            fundDetails.setOrderId(order.getId());
            fundDetails.setOrderNo(order.getOrderNo());
            fundDetails.setFundType(2);
            fundDetails.setOrderTotalMoney(order.getGoodsTotalMoney());
            fundDetails.setVariableAmount(order.getOrderTotalMoney());
            fundDetailsService.insertFundDetails(fundDetails);
        }


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setSignForReceipt(Long orderId) {
        Order order = orderMapper.selectOrderById(orderId);
        CullenUtils.validateDataThrowException(order == null, "订单不存在...");
        CullenUtils.validateDataThrowException(order.getPayStatus() == 3, "订单已完成...");
        CullenUtils.validateDataThrowException(order.getPayStatus() == 10, "订单已退货...");
        CullenUtils.validateDataThrowException(order.getPayStatus() == 1, "订单待发货...");
        CullenUtils.validateDataThrowException(order.getPayStatus() == 4, "订单已取消...");
        CullenUtils.validateDataThrowException(order.getPayStatus() == 8, "订单待审核...");
        CullenUtils.validateDataThrowException(order.getPayStatus() == 0, "订单待支付...");

        Long userId = order.getUserId();
        SysDept sysDept = deptMapper.selectDeptById(order.getDistributorId());

        //查询是否是第一单
        Order order1 = new Order();
        order1.setPayStatus(3);
        order1.setUserId(userId);
        order1.setEnterOrderUserId(order.getEnterOrderUserId());
        List<Order> orders = orderMapper.selectOrderList(order1);
        int enterUserType = 2;
        if (orders == null || orders.size() == 0) {
            //如果是第一单 完成第一单应该更改客户类型为 - vip客户
            enterUserType = 1;
            userMapper.updateUserByEnterUserType(userId);
        }
        //=======================设置订单单号 和 修改订单状态=======================
        orderMapper.setSignForReceipt(orderId, enterUserType);

        //资金明细添加
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectOrderGoodsByOrderId(orderId);
        BigDecimal goodsAmount = new BigDecimal("0");//正常商品总金额
        BigDecimal profitAmount = new BigDecimal("0");//特殊商品总利润
        BigDecimal activityAmount = new BigDecimal("0");//活动赠品


        for (OrderGoods orderGoods : orderGoodsList) {
            Goods goods = goodsMapper.selectGoodsById(orderGoods.getGoodsId());
            CullenUtils.validateDataThrowException(goods == null, "商品: " + orderGoods.getGoodsName() + " 已不存在！");

            if (order.getDistributorId() != null) {
                //是否特殊商品
                if (goods.getGoodsType() == 1 || goods.getGoodsType() == 4 ) {
                    //正常商品
                    System.err.println("============ 正常商品价格 ============ " + goods.getGoodsPrice());
                    goodsAmount = goodsAmount.add(goods.getGoodsPrice().multiply(new BigDecimal(orderGoods.getGoodsQuantity())));//正常商品价格
                    System.err.println("============ 正常商品价格 ============ " + goodsAmount);
                } else if (goods.getGoodsType() == 2) {
                    //特殊商品
                    profitAmount = profitAmount.add(goods.getProfit().multiply(new BigDecimal(orderGoods.getGoodsQuantity())));//特殊商品总金额
                } else if (goods.getGoodsType() == 3) {
                    //赠品
                    activityAmount = activityAmount.add(goods.getGoodsPrice().multiply(new BigDecimal(orderGoods.getGoodsQuantity())));
                }
            }
        }

        if (order.getDistributorId() != null) {
            System.err.println("============ goodsAmount ============ " + goodsAmount);
            System.err.println("============ profitAmount ============ " + profitAmount);
            System.err.println("============ activityAmount ============ " + activityAmount);

            //运费（实付邮费-经销商）rdf43
            BigDecimal userFreight = order.getUserFreight() == null ? BigDecimal.ZERO : order.getUserFreight();
            //(实收邮费-客户)
            BigDecimal freight = order.getFreight() == null ? BigDecimal.ZERO : order.getFreight();
            //签约比例
            SysUser selectUserById = userMapper.selectUserById(sysDept.getUserId());
            BigDecimal signingRatio = selectUserById.getSigningRatio() == null ? BigDecimal.valueOf(25) : BigDecimal.valueOf(selectUserById.getSigningRatio()).divide(BigDecimal.valueOf(100));

            // 实际利润 {（商品金额+实收邮费）*0.99（仓储费）} - 商品金额*比例- 实付邮费 - 特殊商品固定佣金 - 赠品*0.25
            BigDecimal profitTotalAmount = BigDecimal.valueOf(0);//经销商总利润
            //正常商品经销商利润
            if (goodsAmount.compareTo(BigDecimal.ZERO) != 0 || freight.compareTo(BigDecimal.ZERO) != 0) {
                profitTotalAmount = (goodsAmount.add(freight)).multiply(BigDecimal.valueOf(0.99)).subtract(goodsAmount.multiply(signingRatio));
            }
            //实付邮费
            profitTotalAmount = profitTotalAmount.subtract(userFreight);
            //特殊商品总利润
            profitTotalAmount = profitTotalAmount.subtract(profitAmount);
            //赠品
            profitTotalAmount = profitTotalAmount.subtract(activityAmount.multiply(BigDecimal.valueOf(0.25)));

            //保留两位小数
            profitTotalAmount = profitTotalAmount.setScale(2, RoundingMode.HALF_UP);

            //订单提成（经销商）
            FundDetails fundDetails = new FundDetails();
            fundDetails.setUserId(sysDept.getUserId());//扣除对应的是经销商
            fundDetails.setDeptId(sysDept.getDeptId());
            fundDetails.setDeptName(sysDept.getDeptName());
            fundDetails.setOrderId(order.getId());
            fundDetails.setOrderNo(order.getOrderNo());
            fundDetails.setOrderTotalMoney(order.getOrderTotalMoney());
            fundDetails.setFundType(1);
            fundDetails.setType(2);//经销商
            fundDetails.setVariableAmount(profitTotalAmount);
            fundDetailsService.insertFundDetails(fundDetails);
            //用户资金变动（经销商）
            Account account = accountService.selectAccountByUserId(sysDept.getUserId());
            account.setAccountBalance(account.getAccountBalance().add(profitTotalAmount));
            accountService.updateAccount(account);

            //订单提成（总公司）
            FundDetails companyFundDetails = new FundDetails();
            companyFundDetails.setUserId(1L);//利润对应总公司
            SysDept selectDeptById = deptMapper.selectDeptById(userMapper.selectUserById(1L).getDeptId());
            companyFundDetails.setDeptId(selectDeptById.getDeptId());
            companyFundDetails.setDeptName(selectDeptById.getDeptName());
            companyFundDetails.setOrderId(order.getId());
            companyFundDetails.setOrderNo(order.getOrderNo());
            companyFundDetails.setOrderTotalMoney(order.getOrderTotalMoney());
            companyFundDetails.setFundType(1);
            companyFundDetails.setType(1);//公司

            BigDecimal subtract = order.getOrderTotalMoney().subtract(profitTotalAmount);
            companyFundDetails.setVariableAmount(subtract);
            fundDetailsService.insertFundDetails(companyFundDetails);

        }
    }

    /**
     * 商品库存管理
     *
     * @param id 商品ID
     */
    void goodsStock(Long id) {
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectOrderGoodsByOrderId(id);
        for (OrderGoods orderGoods : orderGoodsList) {
            Integer goodsQuantity = orderGoods.getGoodsQuantity();
            Goods goods = goodsMapper.selectGoodsById(orderGoods.getGoodsId());

            CullenUtils.validateDataThrowException(goods.getGoodsStock() < goodsQuantity, "商品 [" + goods.getGoodsName() + "] 库存不足, 无法发货!");

            //商品库存和销量
            if (goods.getGoodsType() == 3 || goods.getGoodsType() == 4) {
                String goodsList = goods.getGoodsList();
                // 去除首尾的方括号
                String trimmed = goodsList.substring(1, goodsList.length() - 1);
                // 按逗号分割字符串
                String[] stringArray = trimmed.split(",");
                for (int i = 0; i < stringArray.length; i++) {

                    Goods goodsById = goodsMapper.selectGoodsById(Long.parseLong(stringArray[i].trim()));
                    CullenUtils.validateDataThrowException(goodsById.getGoodsStock() < goodsQuantity, "商品 [" + goods.getGoodsName() + "] 库存需要购买库存,无法发货!");
                    goodsById.setSalesVolume(goodsById.getSalesVolume() + goodsQuantity);//销量
                    goodsById.setSalesFalse(goodsById.getSalesFalse() + goodsQuantity);//假销量
                    goodsById.setGoodsStock(goodsById.getGoodsStock() - goodsQuantity);//库存
                    goodsMapper.updateGoods(goodsById);
                }

            }
            goods.setSalesVolume(goods.getSalesVolume() + goodsQuantity);//销量
            goods.setSalesFalse(goods.getSalesFalse() + goodsQuantity);//假销量
            goods.setGoodsStock(goods.getGoodsStock() - goodsQuantity);//库存
            goodsMapper.updateGoods(goods);
        }
    }


    @Override
    @SuppressWarnings("all")
    public void cancelOrder(Long id) {
        Order order = orderMapper.selectOrderById(id);
        CullenUtils.validateDataThrowException(order == null, "分销订单不存在...");
        CullenUtils.validateDataThrowException(order.getPayStatus() == 5, "网络异常，请您刷新页面重试...");
        CullenUtils.validateDataThrowException(order.getPayStatus() == 1, "网络异常，请您刷新页面重试...");
        CullenUtils.validateDataThrowException(order.getPayStatus() == 4, "网络异常，请您刷新页面重试...");
        CullenUtils.validateDataThrowException(order.getPayStatus() == 6, "订单已取消...");
        CullenUtils.validateDataThrowException(order.getPayStatus() != 0, "当前订单状态不支持取消...");
        orderMapper.cancelOrder(id);

    }

    @Override
    public void updateOrderEvaluate(Long id) {
        orderMapper.updateOrderEvaluate(id);

    }


    @Override
    public List<OrderVo> orderSettlement(OrderPo orderPo) {
        return orderMapper.orderSettlement(orderPo);
    }

    @Override
    public void userTransfer(Long userId, Long transferUserId, Long companyId) {
        orderMapper.userTransfer(userId, transferUserId, companyId);
    }

    @Override
    public void cancelOrderToAdopt(Long id) {
        Order order = orderMapper.selectOrderById(id);
        order.setCancelStatus(2);
        orderMapper.updateOrder(order);

        if (order.getDistributorId() != null) {
            //资金明细变动
            FundDetails fundDetails = fundDetailsService.selectFundDetailsByOrderNo(2, order.getOrderNo());
            fundDetails.setId(null);
            fundDetails.setFundType(5);
            fundDetailsService.updateFundDetails(fundDetails);

            //用户资金变动
            Account account = accountService.selectAccountByUserId(order.getEnterOrderUserId());
            account.setAccountBalance(account.getAccountBalance().add(order.getOrderTotalMoney()));
            accountService.updateAccount(account);
        }
    }

    @Override
    public void orderTK(String orderNo) {
        Order order = orderMapper.selectOrderByOrderNo(orderNo);
        order.setPayStatus(10);
        orderMapper.updateOrder(order);
    }

    @Override
    public void cancelOrderNotAdopt(Long id, String reasonForCancel) {
        Order order = orderMapper.selectOrderById(id);
        order.setCancelStatus(3);
        order.setReasonForCancel(reasonForCancel);
        orderMapper.updateOrder(order);
    }

    @Override
    public void refundOrder(Order orderPo) {
        Order order = orderMapper.selectOrderById(orderPo.getId());
        CullenUtils.validateDataThrowException(order.getPayStatus() != 3, "不是正常的已收货订单不能退款！");

        if (order.getDistributorId() != null) {
            //退货资金处理

            SysDept selectDeptById = deptMapper.selectDeptById(order.getDistributorId());

            FundDetails fundDetails = new FundDetails();
            fundDetails.setOrderNo(order.getOrderNo());
            fundDetails.setUserId(selectDeptById.getUserId());
            fundDetails.setOrderId(order.getId());
            fundDetails.setDeptId(order.getDistributorId());
            fundDetails.setDeptName(order.getCompanyName());
            fundDetails.setOrderTotalMoney(order.getOrderTotalMoney());
            fundDetails.setVariableAmount(orderPo.getRefundPayment());
            fundDetails.setFundType(11);
            fundDetails.setRemark(orderPo.getRemark());
            fundDetailsService.insertFundDetails(fundDetails);//添加资金明细

            Account account = accountService.selectAccountByUserId(selectDeptById.getUserId());
            account.setAccountBalance(account.getAccountBalance().add(orderPo.getRefundPayment()));
            accountService.updateAccount(account);//修改余额
        }
        orderMapper.refundOrder(orderPo.getId());
    }


}
